<?php
class Report extends Controller
{
	private  $_template_f; 
	private $_numShowItem = 10;
	private $_lang;
	function __construct()
	{
		parent::Controller();
		$this->_lang = $this->mycommon->getLangCode();
		$this->load->language('common', $this->_lang);
        
		$this->load->language('banner/banner', $this->_lang);
		$common_lang = $this->lang->line('common_lang');
		if(!$this->session->userdata('uname'))
		{
			redirect(site_url('login/'));
			die();
		}
		else
		{
			$permitid = $this->session->userdata('permitid');
			if(!is_numeric($permitid) || $permitid > -1)
			{
				show_error($common_lang['access_denied']);
				die();
			}
		}
		$this->_template_f = $this->config->item('template_f');
		$this->load->helper('breadcrumb');
        $this->load->model('report/report_model');
        $this->load->model('campaign/campaign_model');
        $this->load->library('mychart');
	}
	
	function _loadHeader($title = '')
	{
		$header = array();
		$header['title'] = $title == '' ? 'Self serving' : $title;
		$header['template_f'] = $this->_template_f;
		
		$header['username'] = '';
		$header['userid'] = '';
		$header['permitid'] = '';
		$header['module_name'] = 'banner';
		$header['lang'] = $this->_lang;
		$header['common_lang'] = $this->lang->line('common_lang');
        
		if($this->session->userdata('uname'))
		{
			$header['username'] = $this->session->userdata('uname');
			$header['userid'] = $this->session->userdata('uid');
			$header['permitid'] = $this->session->userdata('permitid');
		}
		
		 //load header
		$this->load->view($this->_template_f . 'preheader_view');
		$this->load->view($this->_template_f . 'header_view', $header);
	}
	
	function _loadMenu()
	{
		$data = array();
		$data['username'] = '';
		$data['userid'] = '';
		$data['permitid'] = '';
		$data['lang'] = $this->_lang;
		if($this->session->userdata('uname'))
		{
			$data['username'] = $this->session->userdata('uname');
			$data['userid'] = $this->session->userdata('uid');
			$data['permitid'] = $this->session->userdata('permitid');
		}
		$data['common_lang'] = $this->lang->line('common_lang');
        
		$this->load->view($this->_template_f . 'menu_view',$data);
	}
	
	function _loadFooter()
	{
		$this->load->view($this->_template_f . 'footer_view');
	}
	
    function index()
    {
    	$fromDate = $this->input->get('fromdate');
		$fromDate = ($fromDate == '') ? date('Y-m-d', strtotime ( '-6 day' , strtotime (date('Y-m-d')))) : $fromDate;
		
		$todate = $this->input->get('todate');
		$todate = ($todate == '') ? date('Y-m-d') : $todate;
		
        //load header
  		$this->_loadHeader('Self Serving - report summary');
  		//load menu
        $this->_loadMenu();
		
		$fDateTimeStamp = strtotime($fromDate);
		$tDateTimeStamp = strtotime($todate);
		
  		$data = array();
  		$data['fDateYMD'] = date('Y-m-d', $fDateTimeStamp);
  		$data['tDateYMD'] = date('Y-m-d', $tDateTimeStamp);
        $data['fromdate']= date('d-m-Y', $fDateTimeStamp); 
        $data['todate']= date('d-m-Y', $tDateTimeStamp);
        
        
        $data['fdateUrl']= $fromDate; 
        $data['tdateUrl']= $todate;
        
		$data['data']=$report = $this->report_model->selfserving_report_summary( $fromDate, $todate);
		
		$view=$click=$active_unactive=$active_monney=$spent_monney='';
		if(!empty($report['data1'])){
			//bieu do active/unactive
			$percent_active=round(100*$report['data1'][0]['_activeuser']/$report['data1'][0]['_totaluser'],2);
			$percent_unactive=100-$percent_active;
			$active_unactive="{name:'Kích hoạt',vote:".$report['data1'][0]['_activeuser'].",y:".$percent_active."}";
			$active_unactive.=",{name:'Chưa kích hoạt',vote:".$report['data1'][0]['_unactiveuser'].",y:".$percent_unactive."}";
			//bieu do nap tien/ nguoi active
			if($report['data1'][0]['_activeuser']!=0){
				$percent_monney=round(100*$report['data1'][0]['_monneyuser']/$report['data1'][0]['_activeuser'],2);
				$percent_unmonney=100-$percent_monney;
				
				$active_monney.="{name:'Chưa nạp tiền',vote:".($report['data1'][0]['_activeuser']-$report['data1'][0]['_monneyuser']).",y:".$percent_unmonney."}";
				$active_monney.=",{name:'Nạp tiền',vote:".$report['data1'][0]['_monneyuser'].",y:".$percent_monney."}";
			}
			//bieu do so nguoi tieu tien / so nguoi nap
			if($report['data1'][0]['_monneyuser']!=0){
				$percent_spent=round(100*$report['data1'][0]['_spentuser']/$report['data1'][0]['_monneyuser'],2);
				$percent_unspent=100-$percent_spent;
				$spent_monney="{name:'Người tiêu tiền',vote:".$report['data1'][0]['_spentuser'].",y:".$percent_spent."}";
				$spent_monney.=",{name:'Nạp nhưng chưa tiêu ',vote:".($report['data1'][0]['_monneyuser']-$report['data1'][0]['_spentuser']).",y:".$percent_unspent."}";
			}
			
		}
		
		$data['active_unactive']=$active_unactive;
		$data['active_monney']=$active_monney;
		$data['spent_monney']=$spent_monney;
		
        $data['banner_lang']=$this->lang->line('banner_lang');
  		$this->load->view($this->_template_f.'report/report_view',$data);

  		$this->_loadFooter();
    }

    function cpcdomain()
    {
    	$domainNumItem = 20;
    	$tdate = trim($this->input->get('tdate'));
    	$tdate = ($tdate == '') ? date('d-m-Y') : date('d-m-Y', strtotime($tdate));
    	$fdate = trim($this->input->get('fdate'));
    	$fdate = ($fdate == '') ? date('d-m-Y', strtotime ( '-6 day' , strtotime(date('d-m-Y')))) : date('d-m-Y', strtotime($fdate));
		$export = trim($this->input->get('exp'));
		$cPage = trim($this->input->get('p', true));
		$cPage = (is_numeric($cPage) && $cPage > 0) ? $cPage : 1;
		if($export == 'cvs')
		{
			$expStrDomain = trim($_POST['txtexp']);
			if($expStrDomain != '')
			{
				$fromDate = date('d-m-Y', strtotime($fdate));
				$toDate = date('d-m-Y', strtotime($tdate));
				$lstDomain = json_decode($expStrDomain);
				$filename = "cpc_domain_report_". $fromDate . "_" . $toDate;
                header("Content-type: application/vnd.ms-excel");
                header("Content-disposition: csv" . $fromDate . "_" . $toDate . ".csv");
                header( "Content-disposition: filename=".$filename.".csv");
                
                $csv_output = '';
				$csv_output .= "Time: " .	$fromDate . ' - ' . $toDate . "\n";
				$csv_output .= "\n";
                $csv_output .= "Domain\t";
                $csv_output .= "Group Domain\t";
                $csv_output .= "Price\t";
                $csv_output .= "Total Click\t";
                $csv_output .= "Total Real Click\t";
                $csv_output .= "Total view\t";
                $csv_output .= "CTR (%)";
                $csv_output .= "\n";
                			                
                foreach($lstDomain as $dItem)
                {
					$csv_output .= trim($dItem->domain) . "\t";
                	$csv_output .= trim($dItem->gdomain) . "\t";
                	$csv_output .= trim($dItem->price) . "\t";
                	$csv_output .= trim($dItem->tc) . "\t";
                	$csv_output .= trim($dItem->rc) . "\t";
                	$csv_output .= trim($dItem->v) . "\t";
                	$csv_output .= trim($dItem->ctr);
                	$csv_output .= "\n";
                }	                
                print $csv = chr(255).chr(254).mb_convert_encoding($csv_output, "UTF-16LE", "UTF-8");
                exit;
       		}
		}
		else if ($export == 'cvsdate')
		{
			$expStrDomain = trim($_POST['txtexpdate']);
			if($expStrDomain != '')
			{
				$fromDate = date('d-m-Y', strtotime($fdate));
				$toDate = date('d-m-Y', strtotime($tdate));
				$lstDomain = json_decode($expStrDomain);
				$filename = "cpc_domain_report_by_date_". $fromDate . "_" . $toDate;
                header("Content-type: application/vnd.ms-excel");
                header("Content-disposition: csv" . $fromDate . "_" . $toDate . ".csv");
                header( "Content-disposition: filename=".$filename.".csv");
                
                $csv_output = '';
				$csv_output .= "Time: " .	$fromDate . ' - ' . $toDate . "\n";
				$csv_output .= "\n";
                $csv_output .= "Date\t";
                $csv_output .= "Total Click\t";
                $csv_output .= "Total Real Click\t";
                $csv_output .= "Total view\t";
                $csv_output .= "CTR (%)";
                $csv_output .= "\n";
                			                
                foreach($lstDomain as $dItem)
                {
					$csv_output .= trim($dItem->dt) . "\t";
                	$csv_output .= trim($dItem->tc) . "\t";
                	$csv_output .= trim($dItem->rc) . "\t";
                	$csv_output .= trim($dItem->v) . "\t";
                	$csv_output .= trim($dItem->ctr);
                	$csv_output .= "\n";
                }	                
                print $csv = chr(255).chr(254).mb_convert_encoding($csv_output, "UTF-16LE", "UTF-8");
                exit;
       		}
		}
		else
		{
			$lstPartnerDomain = $this->report_model->cpc_domain_report(4, '', '', '');
			$lstDomain = $this->report_model->cpc_domain_report(1, '', '', '');
			
			$strPartnerCrc = '';
			foreach($lstPartnerDomain as $item)
			{
				foreach($lstDomain as $it)
				{
					if(stripos(strtolower(trim($item['pname'])), strtolower(trim($it['domaingroup']))) !== false)
					{
						$strPartnerCrc .= '-' . $it['groupcrc'] . ',';
						break;
					}
				}
			}
								
			$totalDomain = count($lstDomain);
			$strGroupCrc = '';
			$pCount = ($totalDomain > $domainNumItem) ? ceil($totalDomain/$domainNumItem) : 1;
			$pCount = ($totalDomain > 0) ? $pCount : 0;
			$arrShow = array();
			if($totalDomain > $domainNumItem)
			{
				$start = ($cPage - 1) * $domainNumItem;
				$end = $cPage * $domainNumItem; 
				for($i = $start; $i <$end; $i++)
				{
					if(trim($lstDomain[$i]['groupcrc']) != '')
					{
						$strGroupCrc .= ($strGroupCrc == '') ? $lstDomain[$i]['groupcrc'] : ',' . $lstDomain[$i]['groupcrc'];
					}
					$temp = $lstDomain[$i];
					$temp['totalclick'] = '';
					$temp['realclick'] = '';
					$temp['totalview'] = '';
					$temp['ctr'] = '';
					$arrShow[] = $temp;
					$temp = null;
				}
			}
			else
			{
				foreach($lstDomain as $ditem)
				{
					if(trim($ditem['groupcrc']) != '')
					{
						$strGroupCrc .= ($strGroupCrc == '') ? $ditem['groupcrc'] : ',' . $ditem['groupcrc'];
					}
					$temp = $ditem;
					$temp['totalclick'] = '';
					$temp['realclick'] = '';
					$temp['totalview'] = '';
					$temp['ctr'] = '';
					$arrShow[] = $temp;
					$temp = null;
				}
			}
			$numShow = count($arrShow);
			$totalClick = 0;
			$totalRealClick = 0;
			$totalView = 0;
			if($strGroupCrc != '' )
			{
				$lstDomainReportData = $this->report_model->cpc_domain_report(2, date('Y-m-d', strtotime($fdate)), date('Y-m-d', strtotime($tdate)), $strGroupCrc);
				$tmpData = array();
				foreach($lstDomainReportData as $item)
				{
					$tmpData[$item['domaingroupcrc']] = $item;
				}
				
				
				for($i = 0; $i < $numShow; $i++)
				{
					if(isset($tmpData[$arrShow[$i]['groupcrc']]))
					{
						$arrShow[$i]['totalclick'] = $tmpData[$arrShow[$i]['groupcrc']]['totalclick'];
						$totalClick += (int) $arrShow[$i]['totalclick'];
						$arrShow[$i]['realclick'] = $tmpData[$arrShow[$i]['groupcrc']]['realclick'];
						$totalRealClick += (int) $arrShow[$i]['realclick'];
						$arrShow[$i]['totalview'] = $tmpData[$arrShow[$i]['groupcrc']]['totalview'];
						$totalView += (int) $arrShow[$i]['totalview'];
						$arrShow[$i]['ctr'] = (is_numeric($arrShow[$i]['totalview']) && is_numeric($arrShow[$i]['realclick']) && $arrShow[$i]['totalview'] > 0) ? round(($arrShow[$i]['realclick']/$arrShow[$i]['totalview']) * 100, 3) : 'N/A';
					}
				}
			}
			
			//load header
	  		$this->_loadHeader('Self Serving - report cpcdomain');
	  		//load menu
	        $this->_loadMenu();
			
			$data = array();
			$data['strPartnerCrc'] = $strPartnerCrc;
			$data['fromdate'] = $fdate;
			$data['todate'] = $tdate;
			$data['cPage'] = $cPage;
			$data['pCount'] = $pCount;
			$data['lstDomain'] = $arrShow;
			$data['numDomain'] = $totalDomain;
			$data['totalClick'] = $totalClick;
			$data['totalRealClick'] = $totalRealClick;
			$data['totalView'] = $totalView;
			$this->load->view($this->_template_f.'report/domain_cpc_view',$data);
			
			$this->_loadFooter();
		}
    }
    
   	function cpcdomain_ajax()
   	{
		$domainNumItem = 20;
		$data = array();
    	$totalClick = (float) trim($this->input->get('ttc'));
    	$totalRealClick = (float) trim($this->input->get('ttrc'));   			
    	$totalView = (float) trim($this->input->get('ttv'));
		
		$fromdate = $this->input->get('fd');
		$fromdate = strtotime($fromdate) !== false ? $fromdate : date('d-m-Y');
		$todate = $this->input->get('td');
		$todate = strtotime($todate) !== false ? $todate : date('d-m-Y');
		    			
		$cPage = trim($this->input->get('p'));
		$cPage = (is_numeric($cPage) && $cPage > 0) ? $cPage : 1;
		
		if($cPage > 1)
		{
			$dataView = array();
			$lstDomain = $this->report_model->cpc_domain_report(1, '', '', '');
			$totalDomain = count($lstDomain);
			$strGroupCrc = '';
			$pCount = ($totalDomain > $domainNumItem) ? ceil($totalDomain/$domainNumItem) : 1;
			$pCount = ($totalDomain > 0) ? $pCount : 0;
			$arrShow = array();
			if($totalDomain > $domainNumItem)
			{
				$start = ($cPage - 1) * $domainNumItem;
				$end = $cPage * $domainNumItem;
				for($i = $start; $i <$end; $i++)
				{
					if(isset($lstDomain[$i]))
					{
						if(trim($lstDomain[$i]['groupcrc']) != '')
						{
							$strGroupCrc .= ($strGroupCrc == '') ? $lstDomain[$i]['groupcrc'] : ',' . $lstDomain[$i]['groupcrc'];
						}
						$temp = $lstDomain[$i];
						$temp['totalclick'] = '';
						$temp['realclick'] = '';
						$temp['totalview'] = '';
						$temp['ctr'] = '';
						$arrShow[] = $temp;
						$temp = null;
					}
				}
			}
			else
			{
				foreach($lstDomain as $ditem)
				{
					if(trim($ditem['groupcrc']) != '')
					{
						$strGroupCrc .= ($strGroupCrc == '') ? $ditem['groupcrc'] : ',' . $ditem['groupcrc'];
					}
					$temp = $ditem;
					$temp['totalclick'] = '';
					$temp['realclick'] = '';
					$temp['totalview'] = '';
					$temp['ctr'] = '';
					$arrShow[] = $temp;
					$temp = null;
				}
			}
			$numShow = count($arrShow);
			if($strGroupCrc != '' )
			{
				$lstDomainReportData = $this->report_model->cpc_domain_report(2, date('Y-m-d', strtotime($fromdate)), date('Y-m-d', strtotime($todate)), $strGroupCrc);
				$tmpData = array();
				foreach($lstDomainReportData as $item)
				{
					$tmpData[$item['domaingroupcrc']] = $item;
				}						
				
				for($i = 0; $i < $numShow; $i++)
				{
					if(isset($tmpData[$arrShow[$i]['groupcrc']]))
					{
						$arrShow[$i]['totalclick'] = $tmpData[$arrShow[$i]['groupcrc']]['totalclick'];
						$totalClick += (int) $arrShow[$i]['totalclick'];
						$arrShow[$i]['realclick'] = $tmpData[$arrShow[$i]['groupcrc']]['realclick'];
						$totalRealClick += (int) $arrShow[$i]['realclick'];
						$arrShow[$i]['totalview'] = $tmpData[$arrShow[$i]['groupcrc']]['totalview'];
						$totalView += (int) $arrShow[$i]['totalview'];
						$arrShow[$i]['ctr'] = (is_numeric($arrShow[$i]['totalview']) && is_numeric($arrShow[$i]['realclick']) && $arrShow[$i]['totalview'] > 0) ? round(($arrShow[$i]['realclick']/$arrShow[$i]['totalview']) * 100, 3) : 'N/A';
					}
				}
			}
		 	
		 	$dataView['fromdate'] = $fromdate;
		 	$dataView['todate'] = $todate;
		 	$dataView['lstDomain'] = $arrShow;
		 	$dataView['stt'] = (($cPage - 1) * $domainNumItem) + 1;
		 	
		 	$data['totalclick'] = $totalClick;
		 	$data['totalrealclick'] = $totalRealClick;
		 	$data['totalview'] = $totalView;
		 	$data['totalctr'] = '';
		 	
		 	$data['cPage'] = $cPage;
			$data['pCount'] = $pCount;
			$data['numZone'] = $numShow;
			
			if($cPage == $data['pCount'])
			{
				$data['totalctr'] = ($totalView > 0) ? round(($totalRealClick/$totalView)*100, 3) : '';
				$data['totalclick'] = number_format($data['totalclick']);
				$data['totalrealclick'] = number_format($data['totalrealclick']);
				$data['totalview'] = number_format($data['totalview']);
			}
			
			$getZoneInfo = null;
		 	$zoneReport = null;
								
			$data['data'] = $this->load->view($this->_template_f . 'report/domain_cpc_ajax_view', $dataView, true);
		}
		echo json_encode($data);
   	}
    
   	function cpcdomain_ajax_bydate()
   	{
    	$data = array();
    	$data['lstDate'] = array();
    	
		$fromdate = $this->input->post('fd');
		$fromdate = strtotime($fromdate) !== false ? $fromdate : date('d-m-Y');
		$todate = $this->input->post('td');
		$todate = strtotime($todate) !== false ? $todate : date('d-m-Y');
		$strGroupCrc = trim($this->input->post('crc'));
		$arrCrc = explode(',', $strGroupCrc);
		$strGroupCrc = '';
		foreach($arrCrc as $item)
		{
			if(trim($item) != '')
			{
				$strGroupCrc .= $strGroupCrc == '' ? trim($item) : ',' . trim($item);
			}
		}
		$lstDomainReportData = $this->report_model->cpc_domain_report(3, date('Y-m-d', strtotime($fromdate)), date('Y-m-d', strtotime($todate)), $strGroupCrc);
		
		$clickChart = array();
		$realClickChart = array();
		$viewChart = array();
		$ctrChart = array();
		
		$chartStep = (count($lstDomainReportData)<=10)?1:((count($lstDomainReportData)<=14)?2:floor(count($lstDomainReportData)/7));
		$arrDate = array();
		
		$totalClick = 0;
		$totalRealClick = 0;
		$totalView = 0;
		$totalCtr = 'N/A';
		foreach($lstDomainReportData as $item)
		{
			$item['dt'] = date('d-m-Y', strtotime($item['dt']));
			$arrDate[] = $item['dt'];
			$item['ctr'] = (is_numeric($item['totalview']) && is_numeric($item['realclick']) && $item['totalview'] > 0) ? round(($item['realclick']/$item['totalview']) * 100, 3) : 'N/A';
			$clickChart[] = floatval($item['totalclick']);
			$totalClick += floatval($item['totalclick']);
			$realClickChart[] = floatval($item['realclick']);
			$totalRealClick += floatval($item['realclick']);
			$viewChart[] = floatval($item['totalview']);
			$totalView += floatval($item['totalview']);
			$ctrChart[] = floatval($item['ctr']);
			$data['lstDate'][] = $item;
		}
		$totalCtr = ($totalView > 0) ? round(($totalRealClick/$totalView) * 100, 3) : 'N/A';			
			
		$data['clickChart'] = json_encode(array('name'=>'Total Click','data'=>$clickChart,'color'=> '#627AAD'));
		$data['realClickChart'] = json_encode(array('name'=>'Total Real Click','data'=>$realClickChart,'color'=> '#627AAD'));
		$data['viewChart'] = json_encode(array('name'=>'Total view','data'=>$viewChart,'color'=> '#627AAD'));
		$data['ctrChart'] = json_encode(array('name'=>'CTR','data'=>$ctrChart,'color'=> '#627AAD'));
		
	 	$data['fromdate'] = $fromdate;
	 	$data['todate'] = $todate;		 	
		$data['chartStep'] = $chartStep;
		$data['arrDate'] = $arrDate;
		$data['numDate'] = count($arrDate);
		
		$data['totalClick'] = number_format($totalClick);
		$data['totalRealClick'] = number_format($totalRealClick);
		$data['totalView'] = number_format($totalView);
		$data['totalCtr'] = $totalCtr;
		
		$this->load->view($this->_template_f . 'report/domain_cpc_ajax_bydate_view', $data);
   	}
   	
    function groupreport()
    {
        if(!$this->session->userdata('uname')){
			//echo 'unlogin';
			redirect(site_url('login/?url='.site_url('publicreport/budget')));
			die();
		}
		
        $data['fromdate'] = $fromdate = $this->input->get('fromdate');
        $data['todate'] = $todate = $this->input->get('todate');
        $data['lstgroupid'] = $lstgroupid = $this->input->get('id');
        $data_hour = null;
        if($data['fromdate'] == $data['todate'])
        	$data_hour = $this->report_model->get_group_by_hour($lstgroupid, $fromdate);
        	
        $temp = $this->report_model->selfserving_get_group_chart($fromdate,$todate,$lstgroupid);
        $data['data'] = $temp['data1'];
        $data['lstagency'] = $this->report_model->selfserving_get_all_agency();
        $this->_loadHeader();
        $this->_loadMenu();
        
        $title = $temp['data2'][0]['groupname'];
        
        if($data_hour != null)
        {
        	$arrDate = array();
        	$arrData = array();
        	$arrData1 = array();
        	foreach($data_hour as $item)
        	{
        		$arrDate[] = $item->hour.'h';
        		$arrData[] = (int)$item->clicks;
        		$arrData1[] = (int)$item->views;
        	}
        	$data['data1'] = json_encode(array('name'=>strip_tags($title),'data'=>$arrData,'color'=>'#627AAD'));
            $data['data2'] = json_encode(array('name'=>strip_tags($title),'data'=>$arrData1,'color'=>'#627AAD'));
            $data['date'] = json_encode($arrDate);
            $data['step'] = (count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
        }
        else if(count($data['data'])>0)
        {
            foreach($data['data'] as $dt)
            {
                $arrDate[] = date('d/m/Y',strtotime($dt['dt']));
            }
            foreach($data['data'] as $dt1)
            {
                $arrData[] = (int)$dt1['click'];
            }
            foreach($data['data'] as $dt2)
            {
                $arrData1[] = (int)$dt2['view'];
            }
            $data['data1']=json_encode(array('name'=>strip_tags($title),'data'=>$arrData,'color'=>'#627AAD'));
            $data['data2']=json_encode(array('name'=>strip_tags($title),'data'=>$arrData1,'color'=>'#627AAD'));
            $data['date']=json_encode($arrDate);
            $data['step'] =(count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
        }
        $this->load->view($this->_template_f.'report/groupreport_view',$data);
  		$this->_loadFooter();
    }
    
    function domain()
    {
    	if(!$this->session->userdata('uname')){
			echo 'unlogin';
		}
		else
		{
			if($this->session->userdata('permitid') != -1)
			{
				echo 'notright';
			}
		}
		$data = array();
		$data['domain'] = $this->input->get('domain',true);
        $data['fromdate'] = $this->input->get('fromdate');
        $data['todate'] = $this->input->get('todate');
        if($data['fromdate'] == '' || $data['todate'] == '')
        {
        	$data['todate'] = date('Y-m-d');
        	$data['fromdate'] = date('Y-m-d', strtotime ( '-6 day' , strtotime ($data['todate'])));
        }
        
        $data['items'] = $this->report_model->ssv_report_by_site_v2($data['fromdate'], $data['todate'], $data['domain']);
        $data['label'] = array();
        $data['labelTotal'] = array();
        if(count($data['items']) > 0)
        {
        	foreach ($data['items'][0] as $key => $val)
        	{
        		if(strtolower($key) == 'totalcpm7k') continue;
        		if($data['domain'] != '' && strtolower($key) == 'domain') continue;
        		$data['label'][] = $key;
        		//Khoi tao gia tri cho tong
        		if(is_numeric($val) && strpos($key, '(%)') === false) $data['labelTotal'][$key] = 0;
        		else $data['labelTotal'][$key] = '';
        	}
        	
        	//If domain detail: data for chart
        	if($data['domain'] != '')
        	{
        		$data['xNameArr'] = array();
        		$data['clickArr'] = array();
        		$data['totalClickArr'] = array();
        		$nItems = count($data['items']);
        		//for ($i = $nItems - 1; $i >= 0; $i--)
        		for ($i = 0; $i < $nItems; $i++)
        		{
        			$item = &$data['items'][$i];
        			$data['xNameArr'][] = date('d/m/Y', strtotime($item->dt));
            		$data['clickArr'][] = (int)$item->clickfromAd;
            		$data['totalClickArr'][] = (int)$item->totalclick;
        		}
        	}
        	//End
        	else	//Lay so lieu chart tong theo ngay
        	{
        		$rows = $this->report_model->ssv_report_by_site_v2($data['fromdate'], $data['todate'], 1);
        		$data['xNameArr'] = array();
        		$data['clickArr'] = array();
        		$data['totalClickArr'] = array();
        		$nItems = count($rows);
        		//for ($i = $nItems - 1; $i >= 0; $i--)
        		for ($i = 0; $i < $nItems; $i++)
        		{
        			$item = &$rows[$i];
        			$data['xNameArr'][] = date('d/m/Y', strtotime($item->dt));
            		$data['clickArr'][] = (int)$item->clickfromAd;
            		$data['totalClickArr'][] = (int)$item->totalclick;
        		}
        	}
        }
        if($this->input->get('export', true) == 'pdf')
        {
        	$html = $this->load->view($this->_template_f.'report/domainreport_pdf',$data, true);
        	$filename = 'admarket_report_domain_'.date('d.m.Y').'.pdf';
        	$this->load->library('pdfreport');
        	$this->pdfreport->html2pdf($html, $filename, 'L');
        	return;
        }
        elseif($this->input->get('export', true) == 'excel')
        {
        	$this->load->view($this->_template_f.'report/domain_report_excel',$data);
        	return;
        }
        
        if($data['domain'] != '')
        {
        	$this->load->view($this->_template_f.'report/domainreport_detail_v2',$data);
       	}
        else
        {
        	// for config send mail
        	$data['lstCurrConfig'] = $this->report_model->config_domain_email_get_list_user();
        	// end for config send mail
        	
			$this->load->view($this->_template_f.'report/domainreport_view_v2',$data);
       	}
    }
    
    function ajax_domain_report_config_list()
    {
    	if(!$this->session->userdata('uname')){
			echo 'unlogin';
		}
		else
		{
			if($this->session->userdata('permitid') != -1)
			{
				echo 'notright';
			}
			else
			{
				// for config send mail
		    	$data = array();
				$data['lstCurrConfig'] = $this->report_model->config_domain_email_get_list_user();
		    	$this->load->view($this->_template_f.'report/domainreport_email_config_view',$data);
		    	// end for config send mail
			}
		}
		
		
    }
    
	function ajax_domain_config_user($cfid)
	{
		$data = array();
		$data['r'] = '1';
		$data['username'] = '';
		$data['userid'] = '';
		$data['email'] = '';
		$data['report_domain'] = '';
		$data['mess'] = '';
		if(!$this->session->userdata('uname')){
			$data['r'] = '0';
		}
		else
		{
			if($this->session->userdata('permitid') != -1)
			{
				$data['r'] = '2';
			}
		}
		if($data['r'] == '1')
		{
			$cfid = (int) $cfid;
			$cfInfo = $this->report_model->get_domain_report_config_info($cfid);
			if(!empty($cfInfo))
			{
				$data['username'] = $cfInfo['fullname'];
				$data['email'] = $cfInfo['email'];
				$data['report_domain'] = $cfInfo['report_domain'];
				
				$data['mess'] = $cfInfo['mess'];
    			//$data['mess'] = str_ireplace(array("<br />","<br >","<br>","<br/>"), "\r\n", $data['mess']);  			
			}
			else
			{
				$data['r'] = '3';
			}
		}
		echo json_encode($data);
	}
	
	function set_config_domain_email()
	{
		$data = array();
		$data['r'] = '1';
		if(!$this->session->userdata('uname')){
			$data['r'] = '0';
		}
		else
		{
			if($this->session->userdata('permitid') != -1)
			{
				$data['r'] = '2';
			}
		}
		if($data['r'] == '1')
		{
			$cfid = (int) $this->input->post('cfid');
			$domain = $this->mycommon->getSaveSqlStr(trim($this->input->post('d')));
			$fullname = $this->mycommon->getSaveSqlStr(trim($this->input->post('fn')));
			$email = $this->mycommon->getSaveSqlStr(strtolower(trim($this->input->post('m'))));
			
			//$mess =	 str_replace("\r\n", "<br />", trim($this->input->post('mess')));
			$mess = $this->mycommon->getSaveSqlStr($mess);
			if($domain != '' && $fullname != '' && $email != '')
			{
				$this->report_model->config_domain_email_set($cfid, $domain, $fullname, $email, $mess);
			}
		}

		echo json_encode($data);
	}
	
	function delete_config_domain_email()
	{
		$data = array();
		$data['r'] = '1';
		if(!$this->session->userdata('uname')){
			$data['r'] = '0';
		}
		else
		{
			if($this->session->userdata('permitid') != -1)
			{
				$data['r'] = '2';
			}
		}
		if($data['r'] == '1')
		{
			$cfid = (int) $this->input->get('cfid');
			$this->report_model->delete_config_domain_email($cfid);
		}
		
		echo json_encode($data);
	}
	     
    function group_summary_ajax()	//Phan bo theo nhom
    {
    	if(!$this->session->userdata('uname')){
			echo 'unlogin';
		}
		else
		{
			if($this->session->userdata('permitid') != -1)
			{
				echo 'notright';
			}
		}
		
		$fromdate = $this->input->get('fromdate', true);
		$todate = $this->input->get('todate', true);
		
        if($fromdate == '' || $todate == '')
        {
			$fromdate = ($fromdate == '') ? date('Y-m-d', strtotime ( '-6 day' , strtotime (date('Y-m-d')))) : $fromdate;
			$todate = ($todate == '') ? date('Y-m-d') : $todate;
        }
        $data['fromdate'] = $fromdate;
        $data['todate'] = $todate;
        
        //Lay so lieu cho char thong ke theo ngay
        $data['xNameArr'] = array();
        $data['clickArr'] = array();
        $data['realClickArr'] = array();
        $data['clickChargeArr'] = array();
        $data['viewArr'] = array();
        if($fromdate == $todate)
        {
        	$report = $this->report_model->get_report_by_group_byhour($fromdate);
        	foreach ($report as $obj)
	        {
	        	$data['xNameArr'][] = $obj->hour.'h';
	            $data['clickArr'][] = (int)$obj->clicks;
	            $data['viewArr'][] = (int)$obj->views;
	        }
        }
        else
        {
	        $report = $this->report_model->get_report_by_group_bydate($fromdate,$todate,-1);
	        foreach ($report as $obj)
	        {
	        	$data['xNameArr'][] = date('d/m/Y', strtotime($obj->dt));
	            $data['clickArr'][] = (int)$obj->click;
	            $data['clickChargeArr'][] = (int)$obj->clickcharge;
	            $data['realClickArr'][] = (int)$obj->realclick;
	            $data['viewArr'][] = (int)$obj->view;
	        }
        }
        // --
        
    	$data['data'] = $this->report_model->get_report_by_group($fromdate, $todate);
		if(!empty($data['data']))
		{
			//Xu ly du lieu
			$data['totalClick'] = 0;
			$data['totalRealClick'] = 0;
			$data['totalClickCharge'] = 0;
			$data['totalView'] = 0;
			foreach ($data['data'] as $k => $v)
			{
				if($v['groupid'] == -1)	//Tinh tong tat ca cac nhom thong qua nhom tong
				{
					$data['totalClick'] += $v['click'];
					$data['totalRealClick'] += $v['realclick'];
					$data['totalClickCharge'] += $v['clickcharge'];
					$data['totalView'] += $v['view'];
                    
                    if($v['typegroup'] == -100)	//Tinh tong tat ca cac nhom tru muachung
    				{
    					$data['exMcClick'] = $data['totalClick']-$v['click'];
    					$data['exMcRealClick'] = $data['totalRealClick']-$v['realclick'];
    					$data['exMcClickCharge'] = $data['totalClickCharge']-$v['clickcharge'];
    					$data['exMcView'] = $data['totalView']-$v['view'];
     				}
 				}
			}
		}
		//Lay du lieu thong ke theo ngay cho bieu do cot
		$noibo = $this->report_model->get_report_by_group_bydate($fromdate, $todate, 0);
		$khachhang = $this->report_model->get_report_by_group_bydate($fromdate, $todate, 1);
		$noiboArr = array();
		$khachhangArr = array();
		foreach ($noibo as $i=>$obj) $noiboArr[$obj->dt] = & $noibo[$i];
		foreach ($khachhang as $i=>$obj) $khachhangArr[$obj->dt] = & $khachhang[$i];
		$data['chartBar1_label'] = array();
		$data['chartBar1_click_NB'] = array();
		$data['chartBar1_click_KH'] = array();
		$data['chartBar1_ctr_NB'] = array();
		$data['chartBar1_ctr_KH'] = array();
		foreach ($noiboArr as $i=>$obj)
		{
			$date = new DateTime($i);
			if(!isset($khachhangArr[$i])) continue;
			$data['chartBar1_label'][] = $date->format('d-m-Y');
			$data['chartBar1_click_NB'][] = $noiboArr[$i]->realclick;
			$data['chartBar1_ctr_NB'][] = $noiboArr[$i]->ctr;
			$data['chartBar1_click_KH'][] = $khachhangArr[$i]->realclick;
			$data['chartBar1_ctr_KH'][] = $khachhangArr[$i]->ctr;
		}
		
        echo $this->load->view($this->_template_f.'report/group_summary_report_view',$data, true);
    }
    
    function sendReportDomain()
    {
    	$to = trim($this->input->post('mailTo', true));
    	$cc = trim($this->input->post('mailCc', true));
    	$bcc = trim($this->input->post('mailBcc', true));
    	$domain = $this->input->post('sendRow', true);
    	$mess = trim($this->input->post('mailMess', true));
    	if($to != '' && count($domain) > 0)
    	{
	    	$data = array();
	        $data['fromdate'] = $this->input->post('fromdate', true);
	        $data['todate'] = $this->input->post('todate', true);
	        if($data['fromdate'] == '' || $data['todate'] == '')
	        {
	        	$data['todate'] = date('Y-m-d');
	        	$data['fromdate'] = date('Y-m-d', strtotime ( '-6 day' , strtotime ($data['todate'])));
	        }
	        
	        $data['items'] = $this->report_model->ssv_report_by_site_v2($data['fromdate'], $data['todate']);
	        $data['label'] = array();
	        if(count($data['items']) > 0)
	        {
	        	$data['totalValue'] = array();	//Tinh tong
	        	$exclude_label = array('totalcpm7k', 'inventoryshared(%)', 'totalclick', 'totalview');
	        	foreach ($data['items'][0] as $key => $val)
	        	{
	        		if(in_array(strtolower($key), $exclude_label)) continue;
	        		$data['label'][] = $key;
	        		if(is_numeric($val)) $data['totalValue'][$key] = 0;
	        		else $data['totalValue'][$key] = '';
	        	}
	        	$items = array();
	        	foreach ($data['items'] as $item)
	        	{
	        		if(in_array($item->$data['label'][0], $domain))
	        		{
	        			$items[] = $item;
		        		//Tinh tong cac gia tri so
		        		foreach ($data['label'] as $label)
		        		{
		        			if(is_numeric($item->$label))
		        				$data['totalValue'][$label] += $item->$label;
		        		}
	        		}
	        	}
	        	$data['items'] = $items;
	        }
	        $data['mess'] = $mess;
	        $html = $this->load->view($this->_template_f.'report/domainreport_view_v2_email',$data,true);
	        //Send mail
	        $email = array();
	        $email['to'] = $to;
	        if($cc != '') $email['cc'] = $cc;
	        if($bcc != '') $email['bcc'] = $bcc;
	        $email['subject'] = 'Thống kê doanh thu của site trên hệ thống AdMarket từ ngày '.date('d/m/Y', strtotime($data['fromdate'])).' đến ngày '.date('d/m/Y', strtotime($data['todate']));
	        $email['body'] = $html;
	        $this->mycommon->sendmail($email);
	        echo 1; die();
    	}
    	echo 0; die();
    }
    
	function budget()
	{
		if(!$this->session->userdata('uname')){
			echo 'unlogin';	die();
		}
		
		$data = array();
		$this->load->language('report/report');
		$data['lang'] = $this->lang->line('budget');
		//Get param
		$uid = -1;
		$permitid = (int)$this->session->userdata('permitid');
		$startdate = trim($this->input->get('fd', true));
		$enddate = trim($this->input->get('td', true));
		if($startdate == '' || $enddate == '')
		{
			$startdate = new DateTime();
			$startdate->sub(date_interval_create_from_date_string('7 days'));
			$startdate = $startdate->format('Y-m-d');
			$enddate = date('Y-m-d');
		}

		$page = (int)$this->input->get('page', true);
		if($page < 1) $page = 1;
		//->
		$report = $this->report_model->get_report_financial($uid,$permitid,1,$startdate,$enddate,$page);
		$data['items'] = $report->items;
		//Tinh tong cho cac nhom
		$data['totalForGroup'] = array();
		$tmpIndexGroup = -10;
		for ($i = 0; $i < count($data['items']); $i++)
		{
			$row = &$data['items'][$i];
			if($row->typegroup != $tmpIndexGroup)	//Bat dau 1 group
			{
				$tmpIndexGroup = $row->typegroup;
				$data['totalForGroup'][$tmpIndexGroup] = array();
				$data['totalForGroup'][$tmpIndexGroup]['ad'] = 0;
				$data['totalForGroup'][$tmpIndexGroup]['promotion'] = 0;
				$data['totalForGroup'][$tmpIndexGroup]['sub'] = 0;
			}
			
			$data['totalForGroup'][$tmpIndexGroup]['ad'] += $row->ad;
			$data['totalForGroup'][$tmpIndexGroup]['promotion'] += $row->promotion;
			$data['totalForGroup'][$tmpIndexGroup]['sub'] += $row->sub;
		}
		$data['pages'] = $report->pages->totalpage;
		$data['page'] = $page;
		$data['startdate'] = $startdate;
		$data['enddate'] = $enddate;
		$data['summary'] = $report->summary;
		
		//Tinh du lieu chart theo ngay
		$rowForDate = $this->report_model->get_report_financial($uid,$permitid,0,$startdate,$enddate);
		$data['chart1'] = new stdClass();
		$data['chart1']->label = array();
		$data['chart1']->ad = array();
		$data['chart1']->sub = array();
		$data['chart1']->promotion = array();
		if(count($rowForDate) > 0) foreach ($rowForDate as $item)
		{
			$data['chart1']->label[] = date('d-m-Y', strtotime($item->dt));
			$data['chart1']->ad[] = $item->ad;
			$data['chart1']->sub[] = $item->sub;
			$data['chart1']->promotion[] = $item->promotion;
		}
		//End
		
		//Tinh du lieu chart 2: Tien clickCharge va Tien da su dung
		$clickCharge = $this->report_model->get_report_by_group_bydate($startdate, $enddate, -1);
		$data['chart2'] = new stdClass();
		$data['chart2']->label = array();
		$data['chart2']->money_use = array();
		$data['chart2']->money_click_charge = array();
		
		$c1 = array();
		$c2 = array();
		$cpc_price = $this->config->item('cpc_price_vat');
		foreach ($rowForDate as $i=>$item) $c1[$item->dt] = & $rowForDate[$i];
		foreach ($clickCharge as $i=>$item) $c2[$item->dt] =  & $clickCharge[$i];
		foreach ($c2 as $i=>$item)
		{
			$date = new DateTime($i);
			$data['chart2']->label[] = $date->format('d-m-Y');
			$data['chart2']->money_use[] = $c1[$i]->sub;
			$data['chart2']->money_click_charge[] = $item->clickcharge * $cpc_price;
		}
		//End chart 2

        echo $this->load->view($this->_template_f.'report/budget_index',$data,true);
	}
	
	function budgetagency()
	{
		if(!$this->session->userdata('uname')){
			echo 'unlogin'; die();
		}
		
		$data = array();
		$this->load->language('report/report');
		$data['lang'] = $this->lang->line('budget');
		//Get param
		$uid = -1;
		$groupid = (int)$this->input->get('gid',true);
		$permitid = (int)$this->session->userdata('permitid');
		$startdate = trim($this->input->get('fd', true));
		$enddate = trim($this->input->get('td', true));
		if($startdate == '' || $enddate == '')
		{
			$startdate = new DateTime();
			$startdate->sub(date_interval_create_from_date_string('7 days'));
			$startdate = $startdate->format('Y-m-d');
			$enddate = date('Y-m-d');
		}
		//->
		$report = $this->report_model->get_report_financial_agency($uid,$permitid,$groupid,$startdate,$enddate,1,1000000);
		$data['items'] = $report->items;
		$data['groupid'] = $groupid;
		$data['groupname'] = $this->report_model->getGroupInfo($groupid);
		if($data['groupname'] == null || count((array)$data['groupname']) > 0) $data['groupname'] = $data['groupname']->groupname;
		else $data['groupname'] = 'Online(+sale admarket)';
		$data['startdate'] = $startdate;
		$data['enddate'] = $enddate;
		$data['summary'] = $report->summary;
		//Data for char
		$data['chart1'] = new stdClass();
		$data['chart1']->label = array();
		$data['chart1']->ad = array();
		$data['chart1']->sub = array();
		$data['chart1']->promotion = array();
		foreach ($data['items'] as $row)
		{
			$data['chart1']->label[] = date('d-m-Y', strtotime($row->dt));
			$data['chart1']->ad[] = $row->ad;
			$data['chart1']->sub[] = $row->sub;
			$data['chart1']->promotion[] = $row->promotion;
		}
        echo $this->load->view($this->_template_f.'report/budget_agency',$data,true);
	}
	
	function earn()
	{
		$startdate = trim($this->input->get('startdate', true));
		$enddate = trim($this->input->get('enddate', true));
		if($startdate == '' || $enddate == '')
		{
			$startdate = new DateTime();
			$startdate->sub(date_interval_create_from_date_string('7 days'));
			$startdate = $startdate->format('Y-m-d');
			$enddate = date('Y-m-d');
		}
		$typead = (int)$this->input->get('t',true);
		if($typead == 0) $typead = -1;
		
		$data = array();
		$this->load->language('report/report');
		$data['lang'] = $this->lang->line('budget');
		$data['startdate'] = $startdate;
		$data['enddate'] = $enddate;
		$data['typead'] = $typead;
		$data['items'] = $this->report_model->get_sale_earn($startdate, $enddate, -1, $typead);
		//Tin tong va group theo nhom
		$n = count($data['items']);
		if($n > 0)
		{
			$cGroupId = -1;
			$items = array(); $index = -1;
			foreach ($data['items'] as $row)
			{
				if($cGroupId != $row->groupid)
				{
					$index++;
					$cGroupId = $row->groupid;
					$items[$index] = new stdClass();
					$items[$index]->items = array();
					$items[$index]->group = new stdClass();
					$items[$index]->group->groupname = $row->groupname;
					$items[$index]->group->expensed = 0;
					$items[$index]->group->earn = 0;
				}
				$items[$index]->items[] = $row;
				$items[$index]->group->expensed += $row->expensed;
				$items[$index]->group->earn += $row->earn;
			}
			$data['items'] = $items;
		}
		
		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f.'report/budget_earn_index', $data);
		$this->_loadFooter();
	}
	
	function earnSale()
	{
		$saleid = (int)$this->input->get('id',true);
		$salename = trim($this->input->get('name',true));
		$startdate = trim($this->input->get('startdate', true));
		$enddate = trim($this->input->get('enddate', true));
		if($startdate == '' || $enddate == '')
		{
			$startdate = new DateTime();
			$startdate->sub(date_interval_create_from_date_string('7 days'));
			$startdate = $startdate->format('Y-m-d');
			$enddate = date('Y-m-d');
		}
		$typead = (int)$this->input->get('t',true);
		if($typead == 0) $typead = -1;
		
		$data = array();
		$this->load->language('report/report');
		$data['lang'] = $this->lang->line('budget');
		$data['startdate'] = $startdate;
		$data['enddate'] = $enddate;
		$data['saleid'] = $saleid;
		$data['salename'] = $salename;
		$data['typead'] = $typead;
		$data['items'] = $this->report_model->get_sale_earn_detail($saleid, $startdate, $enddate, $typead);

		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f.'report/budget_earn_sale', $data);
		$this->_loadFooter();
	}
	
	function earnCustomer()
	{
		$saleid = (int)$this->input->get('saleid',true);
		$salename = trim($this->input->get('salename',true));
		$customerid = (int)$this->input->get('id',true);
		$customername = trim($this->input->get('name',true));
		$startdate = trim($this->input->get('startdate', true));
		$enddate = trim($this->input->get('enddate', true));
		if($startdate == '' || $enddate == '')
		{
			$startdate = new DateTime();
			$startdate->sub(date_interval_create_from_date_string('7 days'));
			$startdate = $startdate->format('Y-m-d');
			$enddate = date('Y-m-d');
		}
		$typead = (int)$this->input->get('t',true);
		if($typead == 0) $typead = -1;
		
		$data = array();
		$this->load->language('report/report');
		$data['lang'] = $this->lang->line('budget');
		$data['startdate'] = $startdate;
		$data['enddate'] = $enddate;
		$data['saleid'] = $saleid;
		$data['salename'] = $salename;
		$data['customerid'] = $customerid;
		$data['customername'] = $customername;
		$data['typead'] = $typead;
		$data['items'] = $this->report_model->get_sale_earn_customer($saleid, $customerid, $startdate, $enddate, $typead);

		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f.'report/budget_earn_customer', $data);
		$this->_loadFooter();
	}
	
	function ajaxTrackingBannerReport()
	{
		$page = (int)$this->input->get('page');
		if($page < 1) $page = 1;
		$data = array();
		//Get date param
		$date = new DateTime();
		$data['todate'] = $date->format('Y-m-d');
		$date = $date->sub(new DateInterval('P6D'));
		$data['fromdate'] = $date->format('Y-m-d');
		
		$data['page'] = $page;
		$data['limit'] = 20;
		$data['items'] = $this->report_model->selfserving_report_banner_tracking($page, $data['limit']);
		$data['pages'] = $data['items']['pages'];
		$data['items'] = $data['items']['items'];
		$this->load->view($this->_template_f.'report/tracking_banner_view', $data);
	}
	
	function ajaxCompareDateChart()
	{
		$data = array();
		$date1 = trim($this->input->get('date1', true));
		$date2 = trim($this->input->get('date2', true));
		if($date1 == '' || $date2 == '') return ;
		
		//so lieu
		$data['xNameArr'] = array();
		$data['clickArr'] = array();
		$data['viewArr'] = array();
		$data['clickArr2'] = array();
		$data['viewArr2'] = array();
		$report = $this->report_model->get_report_by_group_byhour($date1);
		$report2 = $this->report_model->get_report_by_group_byhour($date2);
		
		//index lai cac record
		$tmp1 = null;
		$tmp2 = null;
		$tmp_date = null;
		if(count($report) >= count($report2))
		{
			$tmp1 = $report;
			$tmp2 = $report2;
		}
		else
		{
			$tmp1 = $report2;
			$tmp2 = $report;
			$tmp_date = $date1;
			$date1 = $date2;
			$date2 = $tmp_date;
		}
		$report = array();
		foreach ($tmp1 as $item) $report[$item->hour] = $item;
		$report2 = array();
		foreach ($tmp2 as $item) $report2[$item->hour] = $item;
		unset($tmp1, $tmp2);
		
        foreach ($report as $label	=>	$obj)
	    {
	       	$data['xNameArr'][] = $obj->hour.'h';
	       	
	        $data['clickArr'][] = (int)$obj->clicks;
	        $data['viewArr'][] = (int)$obj->views;
	        if(array_key_exists($label, $report2))
	        {
	        	$data['clickArr2'][] = (int)$report2[$label]->clicks;
	        	$data['viewArr2'][] = (int)$report2[$label]->views;
	        }
	        else
	        {
	        	$data['clickArr2'][] = 0;
	        	$data['viewArr2'][] = 0;
	        }
	    }
	    
	    $date1 = new DateTime($date1);
	    $date1 = $date1->format('d-m-Y');
	    $date2 = new DateTime($date2);
	    $date2 = $date2->format('d-m-Y');
	    $data['date1'] = $date1;
	    $data['date2'] = $date2;
		$this->load->view($this->_template_f.'report/ajax_campare_date_chart', $data);
	}
    function ajaxBannerDefaultReport()
    {
        
        $data['todate']=$todate=date('Y-m-d');
        $fromdate = strtotime ( '-7 day' , strtotime ( $todate ) ) ;
        $data['fromdate'] = date ( 'Y-m-d' , $fromdate );
        
        $page = $this->input->get('page') ? $this->input->get('page') : '1';
        $data['page']=$page = (is_numeric($page) && $page > 0) ? $page : '1';
        
        $rownum = $this->input->get('rownum') ? $this->input->get('rownum') : '30';
        $data['rownum']=$rownum = (is_numeric($rownum) && $rownum > 0) ? $rownum : '30';
        
        $temp = $this->report_model->selfserving_get_banner_defaul($page,$rownum);
        $data['info'] = $temp['banner'];
        $data['totalpage'] = $temp['totalpage']['totalpage'];
        $this->load->view($this->_template_f.'report/ajax_banner_default',$data);
    }
    function boxmc()
   	{
   		$boxMcCampId = 1004460;
        
		$tdate = trim($this->input->get('tdate'));
		$tdate = ($tdate == '') ? date('d-m-Y') : date('d-m-Y', strtotime($tdate));
		$fdate = trim($this->input->get('fdate'));
		$fdate = ($fdate == '') ? date('d-m-Y', strtotime ( '-6 day' , strtotime(date('d-m-Y')))) : date('d-m-Y', strtotime($fdate));
		$strCrc = trim($this->input->get('crc'));
		
		$export = trim($this->input->get('exp'));
		if($export == 'cvs')
		{
			$expStrDomain = trim($_POST['txtexp']);
			if($expStrDomain != '')
			{
				$fromDate = date('d-m-Y', strtotime($fdate));
				$toDate = date('d-m-Y', strtotime($tdate));
				$lstDomain = json_decode($expStrDomain);
				$filename = "boxmc_domain_report_". $fromDate . "_" . $toDate;
                header("Content-type: application/vnd.ms-excel");
                header("Content-disposition: csv" . $fromDate . "_" . $toDate . ".csv");
                header( "Content-disposition: filename=".$filename.".csv");
                
                $csv_output = '';
				$csv_output .= "Time: " .	$fromDate . ' - ' . $toDate . "\n";
				$csv_output .= "\n";
                $csv_output .= "Domain\t";
                $csv_output .= "Total Click\t";
                $csv_output .= "Total Real Click\t";
                $csv_output .= "Total view\t";
                $csv_output .= "CTR (%)";
                $csv_output .= "\n";
                			                
                foreach($lstDomain as $dItem)
                {
					$csv_output .= trim($dItem->domain) . "\t";
                	$csv_output .= trim($dItem->tc) . "\t";
                	$csv_output .= trim($dItem->rc) . "\t";
                	$csv_output .= trim($dItem->v) . "\t";
                	$csv_output .= trim($dItem->ctr);
                	$csv_output .= "\n";
                }	                
                print $csv = chr(255).chr(254).mb_convert_encoding($csv_output, "UTF-16LE", "UTF-8");
                exit;
			}
		}
		else
		{
			$lstReport = $this->report_model->camp_report_bydomain($boxMcCampId, date('Y-m-d', strtotime($fdate)), date('Y-m-d', strtotime($tdate)), $strCrc, 1);
			
			$lstData = array();
			$arrTotal = array();
			$arrTotal['totalclick'] = 0;
			$arrTotal['realclick'] = 0;
			$arrTotal['totalview'] = 0;
			$arrTotal['ctr'] =  '';
			$arrDate = array();
			
			foreach($lstReport as $rItem)
			{
				$rItem['ctr'] = '';
				$rItem['ctr'] = (is_numeric($rItem['totalview']) && is_numeric($rItem['realclick']) && $rItem['totalview'] > 0) ? round(($rItem['realclick']/$rItem['totalview']) * 100, 3) : 'N/A';
				$arrTotal['totalclick'] += is_numeric($rItem['totalclick']) ? $rItem['totalclick'] : 0;
				$arrTotal['realclick'] += is_numeric($rItem['realclick']) ? $rItem['realclick'] : 0;
				$arrTotal['totalview'] += is_numeric($rItem['totalview']) ? $rItem['totalview'] : 0;
				$lstData[] = $rItem;
			}
			
			$arrTotal['ctr'] = (is_numeric($arrTotal['totalview']) && is_numeric($arrTotal['realclick']) && $arrTotal['totalview'] > 0) ? round(($arrTotal['realclick']/$arrTotal['totalview']) * 100, 3) : 'N/A';
			
			$lstReportByDate = $this->report_model->camp_report_bydomain($boxMcCampId, date('Y-m-d', strtotime($fdate)), date('Y-m-d', strtotime($tdate)), $strCrc, 2);
		
			$tcChart = array();
			$rcChart = array();
			$tvChart = array();
			$ctrChart = array();
										
			foreach($lstReportByDate as $item)
			{
				$arrDate[] = $item['dt'];
				$tcChart[] = floatval($item['totalclick']);
				$rcChart[] = floatval($item['realclick']);
				$tvChart[] = floatval($item['totalview']);
			
				
				$ctr = (is_numeric($item['totalview']) && is_numeric($item['realclick']) && $item['totalview'] > 0) ? round(($item['realclick']/$item['totalview']) * 100, 3) : 'N/A';
				$ctrChart[] = floatval($ctr);
			}
			
			$chartStep = (count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
			
			$header = array();
			$header['title'] = 'Box muachung report';
			$header['metaTitle'] = 'Box muachung report';
			$header['metaKeyword'] = 'Box muachung report';
			$header['metaDesc'] = 'Box muachung report';
			$this->_loadHeader($header);
			
			$data = array();
			$data['arrCrc'] = array();
			if(trim($strCrc) != '')
			{
				$arrTmp = explode(',', $strCrc);
				foreach($arrTmp as $item)
				{
					if($item > 0)
					{
						$data['arrCrc'][] = $item;
					}
				}
			}
			$data['strCrc'] = $strCrc;
			$data['tcChart'] = json_encode(array('name'=>'Total Click','data'=>$tcChart,'color'=> '#627AAD'));
			$data['rcChart'] = json_encode(array('name'=>'Total Real Click','data'=>$rcChart,'color'=> '#627AAD'));
			$data['tvChart'] = json_encode(array('name'=>'Total view','data'=>$tvChart,'color'=> '#627AAD'));
			$data['ctrChart'] = json_encode(array('name'=>'CTR','data'=>$ctrChart,'color'=> '#627AAD'));
			$data['chartStep'] = $chartStep;
			
			$data['fromdate'] = $fdate;
			$data['todate'] = $tdate;
			$data['lstData'] = $lstData;
			$data['arrTotal'] = $arrTotal;
			$data['arrDate'] = $arrDate;
			
			$this->load->view($this->_template_f.'report/boxmc_cpc_view',$data);
			
			$this->_loadFooter();
		}
   	}
    function boxmc_detail()
   	{
   		$boxMcCampId = 1004460;
		$tdate = trim($this->input->get('tdate'));
		$tdate = ($tdate == '') ? date('d-m-Y') : date('d-m-Y', strtotime($tdate));
		$fdate = trim($this->input->get('fdate'));
		$fdate = ($fdate == '') ? date('d-m-Y', strtotime ( '-6 day' , strtotime(date('d-m-Y')))) : date('d-m-Y', strtotime($fdate));
		$strCrc = trim($this->input->get('crc'));
		$export = trim($this->input->get('exp'));
		
		if($export == 'cvs')
		{
			$expStrDomain = trim($_POST['txtexp']);
			if($expStrDomain != '')
			{
				$fromDate = date('d-m-Y', strtotime($fdate));
				$toDate = date('d-m-Y', strtotime($tdate));
				$lstDomain = json_decode($expStrDomain);
				$filename = "boxmc_detail_domain_report_". $fromDate . "_" . $toDate;
                header("Content-type: application/vnd.ms-excel");
                header("Content-disposition: csv" . $fromDate . "_" . $toDate . ".csv");
                header( "Content-disposition: filename=".$filename.".csv");
                
                $csv_output = '';
				$csv_output .= "Time: " .	$fromDate . ' - ' . $toDate . "\n";
				$csv_output .= "\n";
				$csv_output .= "Date\t";
                $csv_output .= "Domain\t";
                $csv_output .= "Total Click\t";
                $csv_output .= "Total Real Click\t";
                $csv_output .= "Total view\t";
                $csv_output .= "CTR (%)";
                $csv_output .= "\n";
                			                
                foreach($lstDomain as $dItem)
                {
					$csv_output .= trim($dItem->dt) . "\t";
					$csv_output .= trim($dItem->domain) . "\t";
                	$csv_output .= trim($dItem->tc) . "\t";
                	$csv_output .= trim($dItem->rc) . "\t";
                	$csv_output .= trim($dItem->v) . "\t";
                	$csv_output .= trim($dItem->ctr);
                	$csv_output .= "\n";
                }	                
                print $csv = chr(255).chr(254).mb_convert_encoding($csv_output, "UTF-16LE", "UTF-8");
                exit;
			}
		}
		else
		{
			$lstReport = $this->report_model->camp_report_bydomain($boxMcCampId, date('Y-m-d', strtotime($fdate)), date('Y-m-d', strtotime($tdate)), $strCrc, 3);
			
			$lstData = array();
			$arrTotal = array();
			$arrTotal['totalclick'] = 0;
			$arrTotal['realclick'] = 0;
			$arrTotal['totalview'] = 0;
			$arrTotal['ctr'] =  '';
			$arrDate = array();
			
			$tcChart = array();
			$rcChart = array();
			$tvChart = array();
			$ctrChart = array();
			
			$arrInfo = array();
			
			foreach($lstReport as $rItem)
			{
				$rItem['ctr'] = '';
				$rItem['ctr'] = (is_numeric($rItem['totalview']) && is_numeric($rItem['realclick']) && $rItem['totalview'] > 0) ? round(($rItem['realclick']/$rItem['totalview']) * 100, 3) : 'N/A';
				$arrTotal['totalclick'] += is_numeric($rItem['totalclick']) ? $rItem['totalclick'] : 0;
				$arrTotal['realclick'] += is_numeric($rItem['realclick']) ? $rItem['realclick'] : 0;
				$arrTotal['totalview'] += is_numeric($rItem['totalview']) ? $rItem['totalview'] : 0;
				$lstData[$rItem['dt']][] = $rItem;
				$arrDate[] = $rItem['dt'];
				
				$tcChart[$rItem['domaingroupcrc']][] = floatval($rItem['totalclick']);
				$rcChart[$rItem['domaingroupcrc']][] = floatval($rItem['realclick']);
				$tvChart[$rItem['domaingroupcrc']][] = floatval($rItem['totalview']);
				$ctrChart[$rItem['domaingroupcrc']][] = floatval($rItem['ctr']);
				
				if(!isset($arrInfo[$rItem['domaingroupcrc']]))
				{
					$arrInfo[$rItem['domaingroupcrc']] = array();
					$arrInfo[$rItem['domaingroupcrc']]['domaingroup'] = $rItem['domaingroup'];
					$arrInfo[$rItem['domaingroupcrc']]['domaingroupcrc'] = $rItem['domaingroupcrc'];
				}
			}
			
			$arrTotal['ctr'] = (is_numeric($arrTotal['totalview']) && is_numeric($arrTotal['realclick']) && $arrTotal['totalview'] > 0) ? round(($arrTotal['realclick']/$arrTotal['totalview']) * 100, 3) : 'N/A';
							
			
			$chartStep = (count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
			
			$header = array();
			$header['title'] = 'Box muachung report detail';
			$header['metaTitle'] = 'Box muachung report detail';
			$header['metaKeyword'] = 'Box muachung report detail';
			$header['metaDesc'] = 'Box muachung report detail';
			$this->_loadHeader($header);
			
			$data = array();
			$data['arrCrc'] = array();
			if(trim($strCrc) != '')
			{
				$arrTmp = explode(',', $strCrc);
				foreach($arrTmp as $item)
				{
					if($item > 0)
					{
						$data['arrCrc'][] = $item;
					}
				}
			}
			$data['tcChart'] = array();
			$data['rcChart'] = array();
			$data['tvChart'] = array();
			$data['ctrChart'] = array();
			$tmpIndex = 1;
			foreach($arrInfo as $item)
			{
				if($tmpIndex == 1)
				{
					$color = '#627AAD';
				}
				else if($tmpIndex == 2)
				{
					$color = '#FF9900';
				}
				else 
				{
					$a = rand(128, 255);
					$a = dechex($a);
					$b = rand(64, 255);
					$b = dechex($b);
					$c = rand(128, 255);
					$c = dechex($c);
					$color = '#' . $a.$b.$c;
				}
				$data['tcChart'][]=json_encode(array('name'=>strip_tags($item['domaingroup']),'data'=> $tcChart[$item['domaingroupcrc']],'color'=> $color));
				$data['rcChart'][]=json_encode(array('name'=>strip_tags($item['domaingroup']),'data'=> $rcChart[$item['domaingroupcrc']],'color'=> $color));
				$data['tvChart'][]=json_encode(array('name'=>strip_tags($item['domaingroup']),'data'=> $tvChart[$item['domaingroupcrc']],'color'=> $color));
				$data['ctrChart'][]=json_encode(array('name'=>strip_tags($item['domaingroup']),'data'=> $ctrChart[$item['domaingroupcrc']],'color'=> $color));
            	
            	$tmpIndex++;
			}
			
			$data['strCrc'] = $strCrc;
			$data['chartStep'] = $chartStep;
			
			$data['fromdate'] = $fdate;
			$data['todate'] = $tdate;
			$data['lstData'] = $lstData;
			$data['arrTotal'] = $arrTotal;
			$data['arrDate'] = $arrDate;
			
			$this->load->view($this->_template_f.'report/boxmc_detail_cpc_view',$data);
			
			$this->_loadFooter();
		}
	}
}
?>